package com.wlsk.license.scheduling;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wlsk.license.common.enums.CharterPlateStatusEnum;
import com.wlsk.license.dao.entity.Plate;
import com.wlsk.license.dao.mapper.PlateMapper;
import com.wlsk.license.service.IPlateManageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Component
public class PlateClearTask {

    @Autowired
    private PlateMapper plateMapper;

    @Autowired
    IPlateManageService plateOwnerService;

    /**
     * 定时清理过期的包车牌草稿数据
     * 每天凌晨2点执行一次
     */
    @Scheduled(cron = "0 0 2 * * ?")
    public void clearPlate() {
        try {
            log.info("开始执行包车牌草稿数据清理任务");
            // 计算30天前的时间
            LocalDateTime thirtyDaysAgo = LocalDateTime.now().minusDays(30);

            // 查询30天前的草稿数据
            List<Plate> expiredPlates = plateMapper.selectList(
                    new LambdaQueryWrapper<Plate>()
                            .eq(Plate::getDelFlag, "0")  // 未删除的数据
                            .eq(Plate::getCharterPlateStatus, CharterPlateStatusEnum.DRAFT.getCode())  // 草稿状态
                            .lt(Plate::getApplyTime, thirtyDaysAgo)  // 申请时间超过30天
            );

            if (expiredPlates.isEmpty()) {
                log.info("没有需要清理的过期包车牌草稿数据");
                return;
            }
            log.info("找到 {} 条过期的包车牌草稿数据，开始清理", expiredPlates.size());
            // 批量更新删除标志
            int updatedCount = 0;
            for (Plate plate : expiredPlates) {
                plate.setDelFlag("1");
                plate.setUpdateTime(LocalDateTime.now());
                int result = plateMapper.updateById(plate);
                if (result > 0) {
                    updatedCount++;
                }
            }
            log.info("成功清理 {} 条过期的包车牌草稿数据", updatedCount);
        } catch (Exception e) {
            log.error("执行包车牌草稿数据清理任务时发生异常", e);
        }
    }


    // 每分钟检查一次，避免错过重试窗口
    @Scheduled(fixedRate = 60_000)
    public void retryReprintTasks() {
        plateOwnerService.processReprintRetry();
    }
}
